/**
 * 获取 当前元素 的 指定 祖先 元素 一直找到 BODY 元素结束
 * @param {Element} node  element
 * @param {String} targetStr node | id | class
 */
function getTargetEl(node, targetStr) {
  //   console.log(node, targetStr);
  let search = { searchfor: 'id', done: false, value: undefined };
  let node0 = node;
  if (targetStr.nodeType == 1) {
    search['searchfor'] = 'node';
    searchParentNode(node0);
  } else {
    let a = ['#', '.'].indexOf(targetStr.slice(0, 1));
    search['searchfor'] = a > -1 ? (a == 0 ? 'id' : 'class') : 'all';

    if (search['searchfor'] == 'all') {
      //填充符号 确保 前一位 有占位
      targetStr = '$' + targetStr;
      search['searchfor'] = 'id';
      searchParentNode(node0);
      if (search['done'] == false) {
        search['searchfor'] = 'class';
        searchParentNode(node0);
      }
    } else {
      searchParentNode(node0);
    }
  }

  function searchParentNode(node) {
    if (node.nodeName == 'BODY') {
      return false;
    }
    if (search['searchfor'] == 'id') {
      if (node.id == targetStr.slice(1, undefined)) {
        search['done'] = true;
        search['searchfor'] = 'id';
        search['value'] = node;
      } else {
        node = node.parentNode;
        searchParentNode(node);
      }
    }
    if (search['searchfor'] == 'class') {
      if (node.classList.contains(targetStr.slice(1, undefined))) {
        search['done'] = true;
        search['searchfor'] = 'class';
        search['value'] = node;
      } else {
        node = node.parentNode;
        searchParentNode(node);
      }
    }
    if (search['searchfor'] == 'node') {
      if (node == targetStr) {
        search['done'] = true;
        search['searchfor'] = 'class';
        search['value'] = node;
      } else {
        node = node.parentNode;
        searchParentNode(node);
      }
    }
  }
  //   if (search['done']) {
  //     node = search['value'];
  //   }
  return search;
}

export { getTargetEl };
